<template>
  <div class="common-container">
    <div class="header">
      <div class="header_left">
        <el-button
          class="el_button"
          size="small"
          icon="el-icon-plus"
          @click="addClick"
        >
          新增
        </el-button>
        <el-button
          class="el_button"
          size="small"
          icon="el-icon-delete"
          type="info"
          style="margin-left: 15px"
          @click="onDelClickBatch"
        >
          删除
        </el-button>
        <div class="header_left_line"></div>
        <el-button
          class="el_button"
          size="small"
          type="info"
          @click="onStateBatch(1)"
        >
          批量启用
        </el-button>
        <el-button
          class="el_button"
          size="small"
          type="info"
          style="margin-left: 15px"
          @click="onStateBatch(2)"
        >
          批量停用
        </el-button>
        <div class="header_left_line"></div>
        <el-button class="el_button" size="small" type="info" @click="onRecord">
          执行记录
          <i class="el-icon-arrow-right el-icon--right"></i>
        </el-button>
        <!-- <el-select
          v-model="state"
          placeholder="请选择规则状态"
          style="margin-right: 15px; width: 190px"
          size="small"
          clearable
          @change="searchClick"
        >
          <el-option
            v-for="item in stateList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <el-input
          v-model="search_val"
          placeholder="请输入规则名称"
          clearable
          @clear="clearInput"
          size="small"
          style="width: 220px"
        >
          <el-button
            slot="append"
            :icon="loadingSearch ? 'el-icon-loading' : 'el-icon-search'"
            @click="searchClick"
          >
          </el-button>
        </el-input> -->
      </div>
      <div class="header_right">
        <!-- <el-button
          class="el_button"
          size="small"
          icon="el-icon-plus"
          style="margin-left: 15px"
          @click="addClick"
        >
          新增
        </el-button> -->
        <el-select
          size="small"
          v-model="searchSel"
          slot="prepend"
          placeholder="请选择"
          class="el_Select sel_prepend"
        >
          <el-option label="联动规则名称" value="1"></el-option>
          <el-option label="触发设备型号" value="2"></el-option>
          <el-option label="执行设备型号" value="3"></el-option>
        </el-select>
        <el-input
          placeholder="请输入"
          v-model="search_val"
          style="width: 240px; margin-right: 15px"
          size="small"
          maxlength="20"
          clearable
          @clear="clearInput"
          class="el_input"
        >
          <el-button
            slot="append"
            :icon="loadingSearch ? 'el-icon-loading' : 'el-icon-search'"
            @click="searchClick"
          >
          </el-button>
        </el-input>
      </div>
    </div>
    <div class="content">
      <el-table
        :data="dataList"
        class="table"
        :header-cell-style="headerStyle"
        ref="refTable"
        row-key="id"
        @selection-change="batchSelect"
      >
        <el-table-column
          align="center"
          type="selection"
          :reserve-selection="true"
          width="60"
        ></el-table-column>
        <el-table-column
          align="center"
          label="序号"
          type="index"
          width="80"
          height="30"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="name"
          label="联动规则名称"
          min-width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          prop="triggerDeviceType"
          label="触发设备型号"
          min-width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="触发源"
          min-width="100"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.triggerType == 'all'">全部</el-tag>
            <el-tag v-else-if="scope.row.triggerType == 'org'" type="success"
              >组织机构</el-tag
            >
            <el-tag v-else-if="scope.row.triggerType == 'space'" type="info"
              >场所</el-tag
            >
            <el-tag v-else-if="scope.row.triggerType == 'device'" type="warning"
              >设备</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="executingDeviceType"
          label="执行设备型号"
          min-width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          prop="state"
          label="状态"
          min-width="100"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-switch
              slot="reference"
              active-value="running"
              inactive-value="stopped"
              v-model="scope.row.state"
              active-color="#7367F0"
              @change="changeSwitchGetId(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="createTime"
          label="操作时间"
          min-width="150"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          prop="username"
          label="操作人"
          min-width="150"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          prop="description"
          label="场景描述"
          min-width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column align="center" label="操作" width="150">
          <template slot-scope="scope">
            <!-- <el-tooltip
              class="item"
              effect="dark"
              :content="scope.row.state == 'stopped' ? '开启' : '关闭'"
              placement="bottom"
            >
              <i
                @click="changeSwitchGetId(scope.row)"
                class="iconfont kaiqi tableBtnIcon"
                :style="{
                  color: scope.row.state == 'stopped' ? '#67c23a' : '#f56c6c',
                }"
              ></i>
            </el-tooltip> -->
            <!-- <el-tooltip
              class="item"
              effect="dark"
              content="执行日志"
              placement="bottom"
            >
              <i
                @click="handleViewLog(scope.row.id)"
                class="iconfont rizhi tableBtnIcon"
              ></i>
            </el-tooltip> -->
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑"
              placement="bottom"
            >
              <i
                @click="editClick(scope.row)"
                class="iconfont tianxie tableBtnIcon"
              ></i>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="bottom"
            >
              <i
                @click="onDel(scope.row.id)"
                class="iconfont shanchu tableBtnIcon"
              ></i>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="page"
        :limit.sync="limit"
        :pageSizes="[10, 20, 30, 50]"
        @pagination="getDataList"
        class="pagination"
      />
    </div>
    <div
      class="custom-dialog"
      v-if="isShowRuleOperate"
      :style="{ 'z-index': isShowRuleOperate ? 1 : -1 }"
    >
      <ruleOperate ref="refRuleOperate" :editData="editData"></ruleOperate>
    </div>
    <div
      class="custom-dialog"
      v-if="isShowRecord"
      :style="{ 'z-index': isShowRecord ? 1 : -1 }"
    >
      <executeRecord ref="refExecuteRecord" :logId="logId"></executeRecord>
    </div>
    <addRule ref="refaddRule" :editData="editData"></addRule>
    <!-- <editRule ref="refeditRule" :editData="editData"></editRule> -->
    <logDialog ref="reflogDialog" :logId="logId"></logDialog>
  </div>
</template>

<script>
import {
  reqRulePage,
  reqRuleRemove,
  reqRuleState,
  reqRuleRemoveByIds,
  reqRuleStateBatch,
} from "@api/rule.js";
import Pagination from "@components/Pagination.vue";
import tableStyleMixin from "@mixin/table-style";
import addRule from "./components/addRule.vue";
// import editRule from "./components/editRule.vue";
import ruleOperate from "./components/ruleOperate.vue";
import executeRecord from "./components/executeRecord.vue";
import { mapState } from "vuex";
import logDialog from "./components/logDialog.vue";

export default {
  name: "",
  components: { Pagination, addRule, logDialog, ruleOperate, executeRecord },
  mixins: [tableStyleMixin],
  data() {
    return {
      search_val: "",
      searchSel: "1", //名/手机号
      state: "",
      loadingSearch: false, //查询按钮loading
      dataList: [],
      limit: 10,
      page: 1,
      total: 0,
      orgId: "",
      editData: {}, //修改数据

      type: "",
      typeList: [
        {
          id: "scene",
          name: "场景联动",
        },
        {
          id: "flow",
          name: "数据流转",
        },
      ],
      stateList: [
        {
          id: "running",
          name: "已启用",
        },
        {
          id: "stopped",
          name: "未启用",
        },
      ],
      projectList: [], //单位数据
      sysInstanceIndex: 1,
      sysInstanceTotalPages: 10,
      logId: "",
      isShowRuleOperate: false,

      batchDataList: [],

      // 执行记录
      isShowRecord: false,
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  created() {
    this.getDataList();
  },
  mounted() {},
  methods: {
    // 序号
    indexMethod(index) {
      return index + 1 + (this.page - 1) * this.limit;
    },
    changeSwitchGetId(row) {
      if (row.state == "stopped") {
        this.$confirm("此操作将停止该规则, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            row.state = "stopped";
            let res = await reqRuleState({
              id: row.id,
              state: row.state,
            });
            this.$modal.notifySuccess("停止成功");
          })
          .catch(() => {
            row.state = "running";
          });
      } else {
        this.$confirm("此操作将开启该规则, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            row.state = "running";
            let res = await reqRuleState({
              id: row.id,
              state: row.state,
            });
            this.$modal.notifySuccess("开启成功");
          })
          .catch(() => {
            row.state = "stopped";
          });
      }
    },
    // 选择单位
    changeOrgId() {
      this.page = 1;
      this.limit = 10;
      this.getDataList();
    },

    // 获取单位列表
    async OrgList(flag) {
      var res = await reqRulePage(this.sysInstanceIndex, 10, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        tenantId: this.user.tenantId,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      if (flag) {
        this.orgId = res.data.rows[0].id;
      }
      this.sysInstanceTotalPages = res.data.total;
      this.projectList = [...this.projectList, ...res.data.rows];
    },

    // 获取列表
    async getDataList() {
      let triggerDeviceType = "";
      let executingDeviceType = "";
      let name = "";
      this.searchSel == 1
        ? (name = this.search_val)
        : this.searchSel == 2
        ? (triggerDeviceType = this.search_val)
        : (executingDeviceType = this.search_val);
      const res = await reqRulePage(this.page, this.limit, {
        name,
        triggerDeviceType,
        executingDeviceType,
        state: this.state,
        tenantId: this.user.tenantId,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      let { rows, total } = res.data;
      if (rows.length) {
        rows.forEach((item) => {
          // 将时间戳转换为Date对象
          var date = new Date(Number(item.createAt));
          // 获取年、月、日
          var year = date.getFullYear();
          var month = date.getMonth() + 1; // getMonth()返回的月份是从0开始的，所以需要+1
          var day = date.getDate();
          var hour = date.getHours();
          var minute = date.getMinutes();
          var second = date.getSeconds();

          // 将年、月、日转换为两位数的格式
          year = year.toString().padStart(4, "0");
          month = month.toString().padStart(2, "0");
          day = day.toString().padStart(2, "0");
          hour = hour.toString().padStart(2, "0");
          minute = minute.toString().padStart(2, "0");
          second = second.toString().padStart(2, "0");

          // 组合成年月日格式
          item.createAt = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
        });
      }
      this.dataList = rows;
      this.total = total;
    },

    // 点击复选框触发，可跨分页选择
    batchSelect(arr) {
      console.log(arr, "arr");
      this.batchDataList = arr;
    },

    // 搜索
    async searchClick() {
      this.page = 1;
      this.limit = 10;
      this.loadingSearch = true;
      await this.getDataList();
      this.loadingSearch = false;
    },
    // 清空
    clearInput() {
      this.page = 1;
      this.limit = 10;
      this.getDataList();
    },
    getInitDataList() {
      this.page = 1;
      this.limit = 10;
      this.getDataList();
    },
    // 清除请求
    nameClear() {
      this.getInitDataList();
    },
    // 新增
    addClick() {
      this.editData = {};
      this.isShowRuleOperate = true;

      // this.$refs.refaddRule.dialogVisible = true;
    },
    // 编辑
    editClick(row) {
      this.editData = JSON.parse(JSON.stringify(row));
      // this.$refs.refaddRule.dialogVisible = true;

      this.isShowRuleOperate = true;

      // this.$refs.refeditRule.OrgList()
      // this.$refs.refeditRule.dialogVisible = true;
      // this.$refs.refeditRule.Maintenance(this.editData.id)
    },
    // 日志
    handleViewLog(id) {
      this.logId = id;
      this.$refs.reflogDialog.dialogVisible = true;
    },
    // 执行记录
    onRecord() {
      this.isShowRecord = true;
      this.$nextTick(() => {
        this.$refs.refExecuteRecord.page = 1;
        this.$refs.refExecuteRecord.getData();
      });
    },
    // 批量启用
    async onStateBatch(type) {
      if (!this.batchDataList.length)
        return this.$modal.notifyWarning("请先选择规则");
      let msg = type == 1 ? "是否确定为批量启用?" : "是否确定为批量停用?";
      const result = await this.$confirm(msg, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(() => {});
      if (result !== "confirm") return;
      let res = await reqRuleStateBatch({
        id: this.batchDataList.map((item) => item.id),
        state: type == 1 ? "running" : "stopped",
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("操作成功");
      this.$refs.refTable.clearSelection();
      this.getInitDataList();
    },
    // 批量停用
    async onBatchStop() {
      if (!this.batchDataList.length)
        return this.$modal.notifyWarning("请先选择规则");
      const result = await this.$confirm("是否确定为批量停用?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(() => {});
      if (result !== "confirm") return;
    },

    // 批量删除
    async onDelClickBatch() {
      if (!this.batchDataList.length)
        return this.$modal.notifyWarning("请选择要删除的规则");
      const result = await this.$confirm("确定删除所选项吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(() => {});
      if (result !== "confirm") return;
      let res = await reqRuleRemoveByIds({
        ruleId: this.batchDataList.map((item) => item.id),
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("操作成功");
      this.$refs.refTable.clearSelection();
      this.getInitDataList();
    },

    // 单个删除
    async onDel(id) {
      const result = await this.$confirm("确定删除所选项吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(() => {});
      if (result !== "confirm") return;
      const res = await reqRuleRemove(id);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("删除成功");
      this.getInitDataList();
    },
  },
};
</script>

<style scoped lang="less">
@import url("~@views/style/tablePage.less");

::v-deep .el_button.el-button--small {
  background: #7367f0; 
  color: #fff;
  border: none;
}

// 下拉框加载开始
.div_box {
  height: 276px;
  position: absolute;
  top: -1px;
  left: -1px;
  width: 100%;
  z-index: 9999;
  // background: red;
  // opacity: 0.5;
}

::v-deep .el-loading-mask {
  border-radius: 4px;
}

// 下拉框加载结束

// 弹框
.custom-dialog {
  width: 100%;
  height: 100%;
  position: absolute;
  // z-index: 1;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: @primaryHeaderBgcolor;
}

::v-deep .el-switch__core {
  background: @ruleSwitchBg !important;
  border: 1px solid @primaryBorder !important;
}

::v-deep .el-switch.is-checked .el-switch__core {
  border-color: rgb(115, 103, 240) !important;
  background-color: rgb(115, 103, 240) !important;
}

// ::v-deep .el-switch__core:after {
//   background: @ruleTextTitle !important;
// }

.header_left_line {
  width: 1px;
  height: 30px;
  background-color: @ruleDeviceColor;
  margin: 0 15px;
}

// 查询条件切换
::v-deep .sel_prepend .el-input {
  width: 140px;
}

// 搜索框
::v-deep .el_input .el-input__inner {
  border-left: none !important;
  border-radius: 0px !important;
}

::v-deep .el_Select .el-input__inner {
  border-radius: 0px !important;
}

// 多选框
::v-deep .el-checkbox__inner {
  background-color: transparent !important;
  border: 1px solid @primaryBorder !important;
}

// 按钮 info
::v-deep .el-button--info {
  background: @infoButtonBgColor !important;
  color: @infoButtonextColor !important;

  &:hover {
    background: @infoButtonBgColorHover !important;
    color: @infoButtonTextColorHover !important;
  }
}
</style>
